package com.it.base.thread.aqs.phenomena;

/**
 * 没有添加线程锁的情况
 */

public class DiyAqsDemo {
    /**
     * 剩余库存
     */
    private volatile int stock = 5;

    /**
     * 模拟用户个数
     */
    public static final long USER_COUNT = 100;

    /**
     * 购买
     */
    public void buy() {
        try {
            // 模拟购买的耗时
            Thread.sleep(10);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (stock > 0) {
           System.out.println("购买成功，剩余库存为："+this.stock);
            stock--;
        }
        else {
            System.out.println("购买失败，库存不足，剩余库存为："+this.stock);
        }
    }

    /**
     *  使用volatile
     * @param args
     */
    public static void main(String[] args) {
        DiyAqsDemo diyAqsDemo = new DiyAqsDemo();
        for (int i = 0;i<USER_COUNT;i++){
            Thread thread= new Thread(()->diyAqsDemo.buy(),String.format("第%d位顾客的线程", i + 1));
            thread.start();

        }
    }

}
